import { defineStore } from 'pinia'
import { reqLogin, reqUserInfo, reqLogout } from '@/api/modules/login'
export const useUserInfoStore = defineStore('userInfo', {
  state: () => {
    return {
      token: localStorage.getItem('token_key'),
      name: '',
      avatar: ''
    }
  },
  getters: {},
  actions: {
    async login(phone: string, password: string) {
      try {
        const res = await reqLogin({ phone, password })
        // console.log(res)
        //token存到仓库和本地
        this.token = res.token
        localStorage.setItem('token_key', res.token)
        return 'ok'
      } catch (e) {
        return Promise.reject('failed')
      }
    },
    async getUserInfo() {
      try {
        const res = await reqUserInfo()

        this.name = res.loginName
        this.avatar = res.headImg
        console.log(res)
      } catch (e) {
        return Promise.reject('faild')
      }
    },
    reset() {
      localStorage.removeItem('token_key')
      ;(this.token = ''), (this.name = ''), (this.avatar = '')
    },
    async logout() {
      try {
        await reqLogout()
        this.reset()
      } catch (e) {
        return Promise.reject('failed')
      }
    }
  }
})
